<template>
  <view v-if="orderFailed">
    <view class="submit-order" v-if="purchanseList.length">
      <view class="submit-order__tip" v-if="showTip && purchanseList.length > 1">
        <view>
          <view class="content">
            <icon class="iconfont icon">&#xe8c0;</icon>
            <text>以下订单存在【新订单】【预售订单】可查看。</text>
          </view>
          <icon class="iconfont icon" @tap="showTip = false">&#xe650;</icon>
        </view>
      </view>
      <view class="submit-order__list" v-for="(item, index) in purchanseList" :key="index">
        <view class="title">{{ item.type === 1 ? "新订单" : "预售订单" }}</view>

        <view class="content">
          <scroll-view scroll-x="true">
            <view class="image-box">
              <view v-for="(item1, index1) in item.purchanseGoodsItemsList" :key="index1">
                <a-img-loader mode="aspectFit" :src="get(item1, 'goodsItems.goods.thumbnail', '')" />
              </view>
            </view>
          </scroll-view>
          <view @tap="
            nav(
              `/subpackage/order/pages/purchanse/goods-list?type=${item.type}&pSn=${pSn}`
            )
          ">
            <view class="total">
              <view>共<text>{{ item | quantity }}</text>件</view>
              <icon class="iconfont icon">&#xe641;</icon>
            </view>
          </view>
        </view>
      </view>
      <view class="submit-order__pick-up">
        <view class="time">
          <view>选择业绩时间<text>包含查询</text></view>
          <view @tap="showPopupFunc('achievements')">{{
              form.achieveTime.value
          }}<icon class="iconfont icon"> &#xe641;</icon>
          </view>
        </view>
        <view class="expressage">
          <view>取件方式</view>
          <view @tap="showPopupFunc('take-goods')">
            <view class="name">{{ form.sysExpressId.label }}\n<text>根据您选择方式安排取件</text></view>
            <icon class="iconfont icon">&#xe641;</icon>
          </view>
        </view>
        <view class="article-envelope" v-if="form.sysExpressId.value !== 5">
          <template v-if="address">
            <view class="location" @tap="nav('/subpackage/order/pages/purchanse/address/list')">
              <view>
                <icon class="iconfont icon">&#xe605;</icon>
              </view>
              <view>
                <view class="name"><text>{{ address.consignee }} {{ address.mobile }}</text>
                  <icon class="iconfont icon">&#xe641;</icon>
                </view>
                <view class="address">{{ address.fullAddress }}</view>
              </view>
            </view>
          </template>
          <template v-else>
            <view class="add-address" @tap="nav('/subpackage/order/pages/purchanse/address/add')">
              <view>
                <icon class="iconfont icon">&#xeaf3;</icon>
                <view class="add">新增收货地址</view>
              </view>
            </view>
          </template>
          <image :src="'member/envelope.png' | prefixOssUrl" />
        </view>
        <view class="print">
          <view>打印订单价格</view>
          <view>是否打印价格<switch class="switch" :checked="form.printType" @change="switchPrintType"></switch>
          </view>
        </view>
      </view>
      <view class="submit-order__footer">
        <view class="f-left">
          <view class="l-price">
            <view class="p-number"><text>￥</text>{{
                (allTotal.amount + (allTotal.oneThird / 3) * 70) | amountFormat
            }}</view>
            <view class="p-text">共{{ allTotal.quantity }}件/共{{ allTotal.integral + (allTotal.oneThird / 3) }}积分</view>
          </view>
        </view>
        <view class="f-right" @tap="submitOrder">
          <view class="r-btn" :style="!address && form.sysExpressId.value !== 5 && 'opacity: .5;'">提交订单</view>
        </view>
      </view>
      <van-popup :show="popup.show" @click-overlay="popup.show = false" round position="bottom"
        custom-style="height: 90%;border-radius: 20rpx 20rpx 0 0">
        <view class="submit-order__popup">
          <view class="submit-order__achievements" v-show="popup.type === 'achievements'">
            <view class="title">
              <view class="name">
                <text>选择业绩时间</text><text>包含查询</text>
              </view>
              <icon @tap="popup.show = false" class="iconfont icon">&#xe650;</icon>
            </view>
            <view class="tip" v-if="form.tip">
              <view class="content">
                <icon class="iconfont icon">&#xe8c0;</icon>
                <text>如需选择业绩时间，点击下面月份即可。</text>
              </view>
              <icon @tap="form.tip = false" class="iconfont icon">&#xe650;</icon>
            </view>
            <view class="select-year">
              <icon class="iconfont icon" @tap="achievementsSwitchYear(-1)">&#xe64f;</icon>
              <view>{{ form.achieveTime.year }}年</view>
              <icon class="iconfont icon" @tap="achievementsSwitchYear(1)">&#xe64f;</icon>
            </view>
            <view class="option-date" @tap="achievementsSelectiveFunc">
              <view class="item" v-for="(item, index) in form.achieveTime.monthYear" :mark:month="item.achieveTime"
                :key="index" :style="
                  item.achieveTime === form.achieveTime.value &&
                  'box-shadow: 0 0 0 2rpx #333;'
                ">
                <view>{{ item.month }}月</view>
                <view>{{ item.integral }}</view>
              </view>
            </view>
          </view>

          <view class="submit-order__take-goods" v-show="popup.type === 'take-goods'">
            <view class="title">
              <view>取件方式</view>
              <icon class="iconfont icon" @tap="popup.show = false">&#xe650;</icon>
            </view>
            <view class="tip" v-if="form.tip">
              <view class="content">
                <icon class="iconfont icon">&#xe8c0;</icon>
                <text>点击以下选择取件方式。</text>
              </view>
              <icon class="iconfont icon" @tap="form.tip = false">&#xe650;</icon>
            </view>
            <view class="express-company">
              <view class="list" v-for="(item, index) in expressList" :key="index">
                <view>{{ item.name }}</view>
                <axq-checkbox :checked="form.sysExpressId.value === item.id" @change="takeGoodsChoice(item)" />
              </view>
            </view>
          </view>
          <view class="button" @tap="popup.show = false">
            <view>确定</view>
          </view>
        </view>
      </van-popup>
    </view>
  </view>
  <purchanse-failed v-else />
</template>
<script>
import { mapState } from "vuex";
import EventBus from "@/event/index";
import { model } from "@/model";
import axqCheckbox from "@/components/checkbox";
import purchanseFailed from "./@fragment/purchanse-failed.vue";
const { PageBo, PurchanseCart, Member } = model.collection;
export default {
  data () {
    return {
      pSn: "",
      formUtil: PurchanseCart.formUtil(),
      purchanseList: [],
      expressList: [],
      memberAddressList: [],
      overtime: 0,
      popup: {
        type: "",
        show: false,
      },
      form: {
        tip: true,
        achieveTime: {
          value: this.$dayjs().format("YYYY-MM"),
          monthYear: [],
          year: "",
        },
        sysExpressId: {
          value: 0,
          label: "未选择",
        },
        printType: true,
      },
      showTip: true,
    };
  },
  components: {
    axqCheckbox,
    purchanseFailed,
  },
  onLoad (params) {
    this.pSn = params.pSn;
    this.achieveList(this.form.achieveTime.value.split("-")[0]);
    this.updateDetails();

    EventBus.$on("memberAddressList", (list) => {
      this.memberAddressList = list;
    });
  },
  filters: {
    quantity (item) {
      return item.purchanseGoodsItemsList.reduce((quantity, item) => {
        return quantity + item.quantity;
      }, 0);
    },
  },
  computed: {
    ...mapState(["now"]),
    orderFailed () {
      return this.overtime ? this.now < this.overtime : true;
    },
    address () {
      return (
        this.memberAddressList.find((item) => item.isDefault) ||
        this.memberAddressList[0]
      );
    },
    allTotal () {
      return this.purchanseList
        .reduce((list, item) => {
          return list.concat(item.purchanseGoodsItemsList);
        }, [])
        .reduce(
          (allTotal, item) => {
            if (
              item.integralGiveDividend === 1 &&
              item.integralGiveDivisor === 3
            ) {
              allTotal.oneThird += item.quantity;
            } else {
              allTotal.amount +=
                item.quantity * (item.amountCost + item.amountCostAbove);
              allTotal.integral +=
                item.quantity *
                (item.integralGiveDividend / item.integralGiveDivisor);
            }
            allTotal.quantity += item.quantity;

            return allTotal;
          },
          {
            quantity: 0,
            amount: 0,
            integral: 0,
            oneThird: 0,
          }
        );
    },
  },
  methods: {
    switchPrintType (e) {
      const { value } = e.detail;
      this.form.printType = value;
    },
    async updateDetails () {
      const res = await PageBo.sendApi("info", {
        params: {
          page: "pagePurchanseUpdate",
        },
        data: {
          pSn: this.pSn,
        },
      });
      if (res.code !== 2000) {
        return;
      }

      this.purchanseList = this.get(res, "data.purchanseList", []);
      this.memberAddressList = this.get(res, "data.memberAddressList", []);
      this.expressList = this.get(res, "data.expressList", []);
      this.overtime = this.get(res, "data.overtime", []);
      this.form.sysExpressId = {
        value: this.expressList[0].id,
        label: this.expressList[0].name,
      };
    },
    async submitOrder () {
      let form = this.formUtil.fill(
        this.formUtil.generator("update", "default"),
        {
          memberAddressId: this.address ? this.address.id : 0,
          printType: Number(!this.form.printType) + 1,
          sysExpressId: this.form.sysExpressId.value,
          achieveTime: this.$dayjs(this.form.achieveTime.value).format(
            "YYYY-MM-DD"
          ),
        }
      );

      if (!form.memberAddressId.value && form.sysExpressId.value !== 5) {
        return;
      }

      const res = await PurchanseCart.sendApi("update", {
        params: {
          pSn: this.pSn,
        },
        data: this.formUtil.validate(form).form,
      });
      if (res.code !== 2000) {
        return;
      }

      this.red(
        this.purchanseList.length > 1 ? '/subpackage/order/pages/purchanse/list' : `/subpackage/order/pages/purchanse/pay?pSn=${this.pSn}&submitOrder=true`
      );
    },
    async achieveList (year) {
      let monthYear = [];
      for (let i = 0; i < 12; i++) {
        monthYear.push({
          achieveTime: `${year}-${`0${i + 1}`.slice(-2)}`,
          month: i + 1
        });
      }

      const res = await Member.sendApi("achieveList", {
        data: {
          query: {
            year,
          },
        },
      });
      if (res.code !== 2000) {
        return;
      }

      let integrateObj = res.data.reduce((obj, item) => {
        obj[item.month] = {
          integral: item.integral,
        };
        return obj
      }, {});

      for (let i = 0; i < monthYear.length; i++) {
        monthYear[i].integral = integrateObj[monthYear[i].month] ? integrateObj[monthYear[i].month].integral : 0
      }
      this.form.achieveTime.year = year;
      this.form.achieveTime.monthYear = monthYear;
    },
    showPopupFunc (type) {
      this.popup.type = type;
      this.form.tip = true;
      this.popup.show = !this.popup.show;
    },
    setFormItem (e, fromItem) {
      this.popup.show = !this.popup.show;
      Object.assign(fromItem, e);
    },
    achievementsSwitchYear (num) {
      this.achieveList(`${Number(this.form.achieveTime.year) + num}`);
    },
    achievementsSelectiveFunc (e) {
      this.form.achieveTime.value = e.mark.month;
    },
    takeGoodsChoice (item) {
      Object.assign(this.form.sysExpressId, {
        value: item.id,
        label: item.name,
      });
    },
  },
};
</script>
<style lang="less" scoped>
page {
  .submit-order {
    padding: 30rpx 0 300rpx 0;
    min-height: 100vh;
    background-color: #eee;
    box-sizing: border-box;

    .submit-order__tip {
      margin-top: -30rpx 0 30rpx;
      height: 90rpx;

      >view {
        position: fixed;
        top: 0;
        z-index: 1;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 30rpx;
        width: 100%;
        height: 90rpx;
        background-color: #fff3cd;
        color: #ff8500;
        box-sizing: border-box;

        .icon {
          margin-top: -13rpx;
          font-size: 36rpx;
        }

        .content {
          color: #ff8500;
          display: flex;
          align-items: center;
          font-size: 28rpx;

          text {
            margin-left: 18rpx;
          }
        }
      }
    }

    .submit-order__list {
      margin: 0rpx 30rpx 30rpx;
      background: #ffffff;
      border-radius: 10rpx;

      .title {
        padding: 28rpx 30rpx;
        height: 90rpx;
        font-size: 36rpx;
        color: #333;
        box-shadow: 0 1rpx 0 0 #e8e8e8;
        box-sizing: border-box;
      }

      .content {
        position: relative;
        padding: 30rpx 150rpx 27rpx 30rpx;
        box-sizing: border-box;

        scroll-view {
          height: 140rpx;

          .image-box {
            display: flex;

            >view {
              flex-shrink: 0;
              margin-right: 10rpx;
              width: 120rpx;
              height: 120rpx;
              overflow: hidden;
              border-radius: 10rpx;
            }
          }
        }

        >view:last-child {
          position: absolute;
          top: 0;
          right: 0;
          display: flex;
          justify-content: center;
          width: 150rpx;
          height: 100%;

          .total {
            display: flex;
            align-items: center;
            margin-top: 79rpx;
            height: fit-content;
            font-size: 20rpx;
            font-weight: 400;
            color: #333;

            text {
              font-weight: bold;
            }

            .icon {
              margin-top: -21rpx;
              font-size: 26rpx;
              color: #c5c5c5;
            }
          }
        }
      }
    }

    .submit-order__pick-up {
      margin: 0 30rpx 30rpx;
      background: #ffffff;
      border-radius: 10rpx;

      >view {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 30rpx;
        font-size: 30rpx;
        color: #333;
        box-sizing: border-box;

        >view:last-child {
          display: flex;
          align-items: center;
        }

        .icon {
          margin: -12rpx -17rpx 0 0;
          font-size: 37rpx;
          color: #c5c5c5;
        }
      }

      .time {
        height: 100rpx;
        box-shadow: 0 1rpx 0 0 #e8e8e8;

        >view:first-child {
          text {
            margin-left: 21rpx;
            font-size: 24rpx;
            color: #ff8500;
          }
        }
      }

      .expressage {
        padding: 33rpx 30rpx 59rpx;
        box-shadow: 0 1rpx 0 0 #e8e8e8;

        >view:last-child {
          color: #666;

          .name {
            white-space: pre;
            text-align: right;
            margin-bottom: -36rpx;
            line-height: 36rpx;

            text {
              font-size: 24rpx;
              color: #ff8500;
            }
          }

          .icon {
            margin-top: -13rpx;
          }
        }
      }

      .article-envelope {
        position: relative;
        padding: 0;

        .location,
        .add-address {
          display: flex;
          align-items: center;
        }

        .location {
          padding: 30rpx 30rpx 41rpx;
          width: 100%;

          >view:first-child {
            flex-shrink: 0;
            width: 50rpx;
            height: 50rpx;
            margin-right: 25rpx;
            background: #ffafaf;
            border-radius: 50%;

            .icon {
              margin: -3rpx 0 0 3rpx;
              color: #e01212;
              font-size: 46rpx;
            }
          }

          >view:last-child {
            width: 100%;
            font-size: 28rpx;

            .name {
              display: flex;
              justify-content: space-between;
              margin-bottom: 15rpx;
              width: 100%;
            }

            .address {
              color: #666;
            }
          }
        }

        .add-address {
          width: 100%;

          >view:last-child {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 100%;

            .add {
              padding: 75rpx 0;
            }

            .icon {
              margin: 0 20rpx 0 0;
              font-size: 50rpx;
              color: #c7c7cc;
            }
          }
        }

        image {
          position: absolute;
          bottom: 0;
          width: 100%;
          height: 6rpx;
        }
      }

      .print {
        height: 100rpx;
        box-shadow: 0 1rpx 0 0 #e8e8e8;

        >view:last-child {
          font-size: 26rpx;
          color: #999;

          .switch {
            margin: 0 -25rpx 0 25rpx;
            transform: scale(0.85);
          }
        }
      }
    }

    .submit-order__achievements,
    .submit-order__take-goods {
      >view {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 30rpx;
        height: 100rpx;
        color: #333;
        box-sizing: border-box;
      }

      .title {
        font-size: 34rpx;
        font-weight: bold;
        border-bottom: 1rpx solid #f1f1f1;

        .icon {
          color: #999;
        }
      }

      .tip {
        height: 90rpx;
        background-color: #fff3cd;
        color: #ff8500;

        .icon {
          margin-top: -13rpx;
          font-size: 36rpx;
        }

        .content {
          color: #ff8500;
          display: flex;
          align-items: center;
          font-size: 28rpx;

          text {
            margin-left: 18rpx;
          }
        }
      }
    }

    .submit-order__achievements {
      .select-year {
        padding: 0 30rpx;
        font-size: 36rpx;
        box-shadow: 0 1rpx 0 0 #e5e5e5;

        >view {
          width: 87%;
          line-height: 40rpx;
          text-align: center;
          box-shadow: 1rpx 0 0 0 #d2d2d2, -1rpx 0 0 0 #d2d2d2;
        }

        .icon {
          margin-top: -10rpx;
        }

        .icon:last-child {
          transform: rotateY(180deg);
        }
      }

      .option-date {
        justify-content: flex-start;
        flex-flow: wrap;
        padding-top: 30rpx;

        >.item {
          width: 150rpx;
          height: 150rpx;
          margin: 0 30rpx 30rpx 0;
          font-size: 30rpx;
          box-shadow: 0 0 0 2rpx #e5e5e5;
          border-radius: 4rpx;
          flex-shrink: 0;
          text-align: center;

          >view:first-child {
            margin: 25rpx 0;
            color: #999;
          }

          >view:last-child {
            font-size: 30rpx;
            font-weight: bold;
            color: #333333;
          }
        }

        >.item:nth-child(4n) {
          margin-right: 0;
        }
      }
    }

    .submit-order__take-goods {
      .express-company {
        flex-flow: wrap;
        height: auto;
        font-size: 30rpx;

        .list {
          display: flex;
          align-items: center;
          justify-content: space-between;
          width: 100%;
          height: 100rpx;
          box-shadow: 0 -1rpx 0 0 #f1f1f1;

          axq-checkbox {
            /deep/ .checkbox {
              position: relative;

              &::before {
                content: "";
                position: absolute;
                width: 300%;
                height: 275%;
              }
            }
          }
        }
      }
    }

    .submit-order__footer {
      position: fixed;
      bottom: 0;
      z-index: 99;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 30rpx;
      width: 100vw;
      height: 120rpx;
      background: #fff;
      box-shadow: 0px -2rpx 3rpx 0px rgba(24, 24, 24, 0.05);
      box-sizing: border-box;

      .f-left {
        .l-price {
          .p-number {
            font-size: 36rpx;
            font-weight: 800;
            color: #fc524c;

            text {
              font-size: 24rpx;
            }
          }

          .p-text {
            text-align: center;
            font-size: 24rpx;
            color: #666;
          }
        }
      }

      .f-right {
        display: flex;
        align-items: center;

        .r-btn {
          width: 256rpx;
          height: 88rpx;
          text-align: center;
          line-height: 88rpx;
          background: #db187c;
          color: #fff;
          border-radius: 44rpx;

          &_delete {
            background: #fe004f;
          }
        }
      }
    }

    .submit-order__popup {
      .button {
        position: absolute;
        bottom: 0;
        display: flex;
        align-items: center;
        padding: 0 30rpx;
        width: 100%;
        height: 148rpx;
        box-shadow: 0 0 11rpx 0 rgba(8, 1, 3, 0.1);
        box-sizing: border-box;

        >view {
          width: 100%;
          height: 90rpx;
          font-size: 34rpx;
          font-weight: bold;
          color: #fff;
          background: #db187c;
          text-align: center;
          line-height: 90rpx;
          border-radius: 6rpx;
        }
      }
    }
  }
}
</style>